<?php
namespace app\api\controller\deerhome\worker;

use app\api\controller\deerhome\worker\BaseAuth;
use think\Db;
use think\Validate;

/**
 * 钱包
 */
class Wallet extends BaseAuth
{
    
    public function index()
    {
        $month=$this->request->param("month","",'trim');
        $where=[];
        $where['jz_worker_id']=$this->_user['id'];
        if(preg_match("/^\d{4}-\d{2}$/",$month)){
            $where['addtime']=['like',$month.'%'];
        }
        $data=[];
        $data['bg']=$this->fixImg("/assets/addons/deerhome/img/worker_bg.jpg");
        $data['money']=$this->_user['money_left'];
        $data['money_drz']=Db::name("deerhome_order")->where("worker_id",$this->_user['id'])->where("worker_price_to_wallet",0)->where("status","in",[3,4,5])->sum("worker_price");
        $data['list']=Db::name("deerhome_worker_money_log")->where($where)->order("id desc")->paginate(10)->each(function($item, $key){
            $item['time']=date("m-d H:i",strtotime($item['addtime']));
            if($item['type']=="服务分成"){
                $item['note']="#".$item['jz_order_sn'];
            }
            return $item;
        });
        $this->ok($data);
    }
    public function price(){
        $this->ok($this->_user['money_left']);
    }
    public function add(){
        $price=$this->request->param("price",0,'floatval');
        if($price<=0){
            $this->err("请输入正确的金额");
        }
        if(\bccomp($price, $this->_user['money_left'],2)==1){
            $this->err("余额不足");
        }
        $worker_card=Db::name("deerhome_worker_card")->where("jz_worker_id",$this->_user['id'])->find();
        if(!$worker_card){
            $this->err("请先填写银行卡信息");
        }
        Db::startTrans();
        try{
            Db::name("deerhome_worker_money_log")->insert([
                'type'=>"服务提现",
                'jz_worker_id'=>$this->_user['id'],
                'price'=>$price*-1,
                'skr'=>$worker_card['uname'],
                'bank'=>$worker_card['bank'],
                'bankcard'=>$worker_card['card'],
                'note'=>"申请提现，等待处理",
                'addtime'=>date("Y-m-d H:i:s")
            ]);
            Db::name("deerhome_worker")->where("id",$this->_user['id'])->setDec("money_left",$price);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->err($e->getMessage());
        }
        $this->ok();
    }
 
}
